Lesson 6 - Logical operators
Conditional expressions can chain together different conditions in order to be more expressive. For example if we wanted to make sure that both variables x and y are bigger than 10 we could use a nested if statement or the logical operator and. The code below shows both solutions. The logical operator version is much easier to work with.
x = 12
y= 43
# nested if solution
if x > 10:
if y>10:
print "both x and y are bigger than 10"
# and operator solution
if x > 10 and y > 10:
print "both x AND y are bigger than 10"
There are three main logical operators.
and - both a and b must be true in order for the whole expression to be true
or - either a or b must be true in order for the whole expression to be true
not - will invert the truth of a statement. True becomes false and visa versa.
x = 3
y = 9
print x == 3 and y == 9 # true
print x == 3 or y ==9 # true
print x == 1 and y == 9 # false
print x == 1 or y == 9 # true
print not x == 3 # false
print (x == 1 and y == 9) or (x == 3 and y == 9) # true
The examples above show how the logical operators can be used. These can be used directly in if statements. The next code example puts a spin on the secret number guessing game by only giving a hint if they are within 20. You can download the code, secretv2.py, here.
guess = input("Enter a number ")
secret = 21
# see if they were close or not!
diff = guess - secret
# diff could be negative!
if diff < 0:
diff = diff * -1
# ensure that guess is within 20
if guess > secret and diff <= 20:
print "guess is too big"
elif guess < secret and diff <=20:
print "guess is too small"
elif guess == secret:
print "Well done you guessed correctly!"
else:
print "Your nowhere near!"